package com.example.meituan.activity.user.farment;


import android.content.Intent;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.SearchView;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;

import com.example.meituan.R;
import com.example.meituan.activity.bean.ShopBean;
import com.example.meituan.activity.man.UpdateShopActivity;
import com.example.meituan.activity.man.frament.ManageHomeFragment;
import com.example.meituan.activity.man.frament.OnItemClickListener;
import com.example.meituan.activity.user.GridLayoutManager;
import com.example.meituan.activity.user.ProductDetialsActivity;
import com.example.meituan.activity.user.adapter.ProductAdapter;
import com.example.meituan.dao.ShopDao;
import com.google.android.material.button.MaterialButton;

import java.util.List;


public class UserHomeFragment extends Fragment implements OnProductClickListener, OnItemClickListener {
    View rootView;
    ShopDao shopDao;
    List<ShopBean> list;
    private ProductAdapter adapter;

    @Override
    public void onItemClick(ShopBean item) {
        Intent intent = new Intent(getContext(), ProductDetialsActivity.class);
        intent.putExtra("shopBean", item); // 使用 putExtra() 方法传递 ShopBean 对象
        startActivity(intent);
    }
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        if (shopDao == null) {
            shopDao = new ShopDao(getActivity());
        }
        rootView = inflater.inflate(R.layout.fragment_user_home, container, false);
        LinearLayout buttonContainer = rootView.findViewById(R.id.button_container);
        String[] shopTypes = getResources().getStringArray(R.array.shop_type_array);
        for (int i = 0; i < shopTypes.length; i++) {
            MaterialButton button = new MaterialButton(rootView.getContext());
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.WRAP_CONTENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT
            );
            button.setLayoutParams(params);
            button.setText(shopTypes[i]);
            button.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#FF0000")));
            button.setTextColor(Color.WHITE);
            button.setTypeface(null, Typeface.BOLD);
            final int index = i;// 因为匿名内部类只能访问final或effectively final变量
            button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    list = shopDao.getAllShopsByType(shopTypes[index]);
                    androidx.recyclerview.widget.RecyclerView recyclerView=rootView.findViewById(R.id.recyclerView);
                    if (list == null || list.isEmpty()) {
                        Toast.makeText(getContext(), "没有数据显示", Toast.LENGTH_SHORT).show();
                        recyclerView.setAdapter(null);
                    } else {
                        adapter = new ProductAdapter(list,this::onProductClick,this::onItemClick);
                        recyclerView.setLayoutManager(new GridLayoutManager(rootView.getContext(), 2));
                        recyclerView.setAdapter(adapter);
                    }

                }

                private void onProductClick(String s) {
                    // 检查片段是否已经附加到活动
                    if (!isAdded()) {
                        Log.w("UserHomeFragment", "Fragment not attached to an Activity.");
                        return;
                    }

                    // 创建新的 ManageHomeFragment 实例并设置参数
                    ManageHomeFragment productFragment = new ManageHomeFragment();
                    Bundle args = new Bundle();
                    args.putString("businessId", s);
                    productFragment.setArguments(args);

                    // 获取FragmentManager，并开始事务
                    FragmentManager fragmentManager = requireActivity().getSupportFragmentManager();

                    // 确保没有正在进行的回退操作
                    if (fragmentManager.isStateSaved()) {
                        Log.w("UserHomeFragment", "Can't perform transactions after onSaveInstanceState");
                        return;
                    }


                    fragmentManager.beginTransaction()
                            .replace(R.id.user_main_frame, productFragment)
                            .addToBackStack(null)
                            .commit();
                }

                private void onItemClick(ShopBean shopBean) {
                    Intent intent = new Intent(getContext(), ProductDetialsActivity.class);
                    intent.putExtra("shopBean", shopBean); // 使用 putExtra() 方法传递 ShopBean 对象
                    startActivity(intent);
                }





            });

            buttonContainer.addView(button);

        }

        list = shopDao.getAllShops();
        androidx.recyclerview.widget.RecyclerView recyclerView=rootView.findViewById(R.id.recyclerView);
        if (list == null || list.isEmpty()) {
            Toast.makeText(getContext(), "没有数据显示", Toast.LENGTH_SHORT).show();
            recyclerView.setAdapter(null);
        } else {
            adapter = new ProductAdapter(list,this::onProductClick,this::onItemClick);
            recyclerView.setLayoutManager(new GridLayoutManager(rootView.getContext(), 2));
            recyclerView.setAdapter(adapter);
        }

        androidx.appcompat.widget.SearchView searchView = rootView.findViewById(R.id.user_home_shop_listView_search);
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                List<ShopBean> list = shopDao.getAllShopsByNameType(query);
                if (list == null || list.isEmpty()) {
                    Toast.makeText(getContext(), "没有数据显示", Toast.LENGTH_SHORT).show();
                    recyclerView.setAdapter(null);
                } else {
                    adapter = new ProductAdapter(list,this::onProductClick,this::onItemClick);
                    recyclerView.setLayoutManager(new GridLayoutManager(rootView.getContext(), 2));
                    recyclerView.setAdapter(adapter);
                }
                return false;
            }

            private void onItemClick(ShopBean shopBean) {
                Intent intent = new Intent(getContext(), ProductDetialsActivity.class);
                intent.putExtra("shopBean", shopBean); // 使用 putExtra() 方法传递 ShopBean 对象
                startActivity(intent);
            }


            public void onProductClick(String businessId) {
                // 检查片段是否已经附加到活动
                if (!isAdded()) {
                    Log.w("UserHomeFragment", "Fragment not attached to an Activity.");
                    return;
                }

                // 创建新的 ManageHomeFragment 实例并设置参数
                ManageHomeFragment productFragment = new ManageHomeFragment();
                Bundle args = new Bundle();
                args.putString("businessId", businessId);
                productFragment.setArguments(args);

                // 获取FragmentManager，并开始事务
                FragmentManager fragmentManager = requireActivity().getSupportFragmentManager();

                // 确保没有正在进行的回退操作
                if (fragmentManager.isStateSaved()) {
                    Log.w("UserHomeFragment", "Can't perform transactions after onSaveInstanceState");
                    return;
                }

                // 执行替换操作
                fragmentManager.beginTransaction()
                        .replace(R.id.user_main_frame, productFragment)
                        .addToBackStack(null) // 可选: 将此事务添加到返回栈，以便用户可以返回
                        .commit();
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                return false;
            }
        });
        return rootView;
    }
    @Override
    public void onProductClick(String businessId) {

        if (!isAdded()) {
            Log.w("UserHomeFragment", "Fragment not attached to an Activity.");
            return;
        }

        ManageHomeFragment productFragment = new ManageHomeFragment();
        Bundle args = new Bundle();
        args.putString("businessId", businessId);
        productFragment.setArguments(args);


        FragmentManager fragmentManager = requireActivity().getSupportFragmentManager();

        if (fragmentManager.isStateSaved()) {
            Log.w("UserHomeFragment", "Can't perform transactions after onSaveInstanceState");
            return;
        }

        // 执行替换操作
        ((FragmentManager) fragmentManager).beginTransaction()
                .replace(R.id.user_main_frame, productFragment)
                .addToBackStack(null) // 可选: 将此事务添加到返回栈，以便用户可以返回
                .commit();
    }
}